//
// Description: 849. Dijkstra求最短路 I
// Created by Loading on 2022/5/18.
//

#include <bits/stdc++.h>

using namespace std;

constexpr int N = 510;
constexpr int INF = 0x3f3f3f3f;

int g[N][N];
int dist[N];
bool st[N];
int n;

int dijkstra() {
    memset(dist, 0x3f, sizeof dist);
    dist[1] = 0;

    for (int i = 0; i < n; ++i) {
        int t = -1;
        for (int j = 1; j <= n; ++j) {
            if (!st[j] && (t == -1 || dist[j] < dist[t])) {
                t = j;
            }
        }

        for (int j = 1; j <= n; ++j) {
            dist[j] = min(dist[j], dist[t] + g[t][j]);
        }

        st[t] = true;
    }

    return dist[n] == INF ? -1 : dist[n];
}

int main() {
    int m;
    cin >> n >> m;
    memset(g, 0x3f, sizeof g);
    for (int i = 0; i < m; ++i) {
        int a, b, c;
        scanf("%d%d%d", &a, &b, &c);
        g[a][b] = min(g[a][b], c);
    }

    cout << dijkstra() << endl;

    return 0;
}